<?php

declare (strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */
namespace App\Model;

use Hyperf\HttpMessage\Upload\UploadedFile;
class Upload extends Model
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected ?string $table = 'upload';
    protected array $hidden = ['path', 'create_time', 'update_time'];
    public static $mimes = ['image/bmp' => 'bmp', 'image/gif' => 'gif', 'image/jpeg' => 'jpg', 'image/png' => 'png', 'image/x-icon' => 'ico'];
    public static function getByMd5($md5)
    {
        return static::where('md5', $md5)->first();
    }
    public static function initByMd5($md5)
    {
        $check = static::getByMd5($md5);
        if ($check == null) {
            throw new \Exception('文件不存在', 500);
        }
        return $check;
    }
    /**
     * 文件上传
     * @param $file
     * @return $this|Upload|false|\Hyperf\Database\Model\Builder|\Hyperf\Database\Model\Model|object
     */
    public function upload($file)
    {
        /** @var UploadedFile $file */
        if (!$file->isValid()) {
            return false;
        }
        $md5 = md5_file($file->getPath());
        $upload = static::getByMd5($md5);
        if ($upload) {
            return $upload;
        }
        if (!file_exists(BASE_PATH . '/public/upload/' . date('Y-m-d'))) {
            mkdir(BASE_PATH . '/public/upload/' . date('Y-m-d'));
        }
        $name = date('Y-m-d') . '/' . time() . rand(1000, 9999) . '.' . $file->getExtension();
        $path = BASE_PATH . '/public/upload/' . $name;
        $file->moveTo($path);
        $data = ['path' => $path, 'url' => env('FILE_URL', 'http://127.0.0.1:8080') . $path, 'size' => $file->getSize(), 'name' => $file->getFilename(), 'mime_type' => $file->getMimeType(), 'md5' => $md5];
        $upload = new static($data);
        $upload->save();
        return $upload;
    }
    /**
     * 接口返回
     * @return array
     */
    public function toApi()
    {
        return [
            'id' => $this->id,
            'path' => stripslashes(($this->path ?? '')),
            'url' => stripslashes(($this->url ?? '')),
            'size' => $this->size ?? 0,
            'name' => $this->name ?? '',
            'mime_type' => $this->mime_type ?? ''
        ];
    }
}